<?php
namespace app\system\controller;

use app\common\model\ShopAttrModel;
use app\common\model\ShopExtendModel;
use app\common\model\ShopGoodsBrandModel;
use app\common\model\ShopGoodsDataModel;
use app\common\model\ShopGoodsModel;
use app\common\model\ShopGoodsSkuModel;
use app\common\model\UserModel;
use think\Request;

class ShopGoodsController extends BaseController
{

    private $goodsCategoryCache;
    private $goodsModel;
    private $goodsDataModel;
    private $goodsSkuModel;
    private $extendModel;

    /**
     * 初始化
     */
    public function __construct(Request $request)
    {
        parent::__construct($request);
        $this->goodsModel         = new ShopGoodsModel();
        $this->goodsDataModel     = new ShopGoodsDataModel();
        $this->extendModel        = new ShopExtendModel();
        $this->goodsSkuModel      = new ShopGoodsSkuModel();
        $this->goodsCategoryCache = $this->getCategory($this->getSiteId(), $this->getUid());
    }

    /**
     * 获取允许操作栏目
     * @param $siteId
     * @param $uid
     * @return array|mixed
     */
    public function getCategory($siteId, $uid)
    {
        $userModel = new UserModel();
        $groupId   = $userModel->where('uid', $uid)->value('group_id');
        $category  = $userModel->getGoodsCategory($siteId, $groupId);
        return $category;
    }

    //商品管理首页
    public function iframe()
    {
        return $this->fetch();
    }

    /**
     * ajax zTree树型
     */
    public function ajaxztree()
    {
        $cate     = $this->goodsCategoryCache;
        $category = [];
        if ($cate) {
            $catTypeName = ['1' => '(频道)', '2' => '(列表)', '3' => '(外链)'];
            foreach ($cate as $cat) {
                $data         = [];
                $data['name'] = $cat['cat_name'] . $catTypeName[$cat['cat_type']];
                switch ($cat['cat_type']) {
                    case '1':
                        $url = 'javascript:;';
                        break;
                    case '2':
                        $url = url('index', ['cid' => $cat['cid']]);
                        break;
                    case '3':
                        $url = 'javascript:;';
                        break;
                }
                $data['id']     = $cat['cid'];
                $data['pId']    = $cat['pid'];
                $data['url']    = $url;
                $data['target'] = 'content';
                if ($cat['_level'] == 2 && $cat['is_son'] == true) {
                    $data['open'] = false;
                } else {
                    $data['open'] = true;
                }
                $category[] = $data;
            }
        }
        return json($category);
    }

    /**
     * 首页
     */
    public function index()
    {
        $map                = [];
        $query              = [];
        $map['site_id']     = $this->getSiteId();
        $query['site_id']   = $this->getSiteId();
        $goodstype          = $this->request->param('goodstype/d', 0);
        $query['goodstype'] = $goodstype;
        switch ($goodstype) {
            case 1:
                $map['is_on_sale'] = 1;
                break;
            case 2:
                $map['is_on_sale'] = 0;
                break;
            case 3:
            case 4:
            case 5;
            case 6:
            case 7:
                $map['promotion_type'] = $goodstype - 2;
                break;
            default:
                break;
        }
        $goodsName = $this->request->param('goods_name');
        if (!empty($goodsName)) {
            $map['goods_name']   = ['like', '%' . $goodsName . '%'];
            $query['goods_name'] = $goodsName;
        }
        $cid = $this->request->param('cid');
        if ($cid > 0) {
            $cids         = array_keys(\org\util\TreeUtil::channelList($this->goodsCategoryCache, $cid, "&nbsp;", 'cid', 'pid'));
            $cids[]       = $cid; //加入当前栏目
            $map['cid']   = ['in', $cids];
            $query['cid'] = $cid;
        }
        $property = $this->request->param('property');
        if (!empty($property)) {
            $map[$property]    = 1;
            $query['property'] = $property;
        }
        $list = $this->goodsModel->where($map)->order('goods_sort desc')->paginate(12, false, [
            'query' => $query,
        ]);
        //echo $this->goodsModel->getLastSql();
        cookie('__GOODSURL__', get_current_url());
        $this->assign('category', $this->goodsCategoryCache);
        $this->assign('goodstype', $goodstype);
        $this->assign('list', $list);
        $this->assign('query', $query);
        return $this->fetch();
    }

    /**
     * 添加
     * @return mixed
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $data            = $this->request->param();
            $data['uid']     = $this->getUid();
            $data['site_id'] = $this->getSiteId();
            $data['is_attr'] = $this->request->has('is_attr') ? '1' : '0';
            $result          = $this->validate($data, 'ShopGoodsValidate');
            if ($result !== true) {
                $this->error($result);
            }
            $result = $this->goodsModel->addData($data);
            if ($result == false) {
                $this->error($this->goodsModel->getError());
            }
            $this->success('添加成功', cookie('__GOODSURL__'));
        }
        $extendList = $this->extendModel->where('site_id', $this->getSiteId())->order('extend_sort')->select();
        $this->assign('unitList', get_dict('103'));
        $this->assign('extendList', $extendList);
        $this->assign('goodsCategory', $this->goodsCategoryCache);
        $this->assign('utype',$this->getUtype());
        return $this->fetch();
    }

    /**
     * 修改
     * @return mixed
     */
    public function edit()
    {
        if ($this->request->isAjax()) {
            $data            = $this->request->param();
            $data['site_id'] = $this->getSiteId();
            $result          = $this->validate($data, 'ShopGoodsValidate');
            if ($result !== true) {
                $this->error($result);
            }
            if (!$this->request->has('extend')) {
                $data['extend'] = '';
            }
            $result = $this->goodsModel->editData($data);
            if ($result == false) {
                $this->error($this->goodsModel->getError());
            }
            $this->success('操作成功！', cookie('__GOODSURL__'));
        }
        $goodsId = $this->request->param('goods_id/d');
        $info    = $this->goodsModel->getInfo($goodsId);
        //sku信息
        if ($info['is_attr'] == 1) {
            $attrModel = new ShopAttrModel();
            $attrIds   = $this->goodsCategoryCache[$info['cid']]['attr_ids'];
            $attrList  = $attrModel->getAttrList($attrIds);
            $this->assign('attrList', $attrList);
        }
        $goodsSkuModel    = new ShopGoodsSkuModel();
        $skuList          = $goodsSkuModel->where('goods_id', $goodsId)->select();
        $info['sku_list'] = $skuList->toArray();
        //扩展信息
        $extendList = $this->extendModel->where('site_id', $this->getSiteId())->order('extend_sort')->select();
        $this->assign('unitList', get_dict('103'));
        $this->assign('extendList', $extendList);
        $this->assign('goodsCategory', $this->goodsCategoryCache);
        $this->assign('info', $info);
        $this->assign('utype',$this->getUtype());
        return $this->fetch();
    }

    /**
     * 拷贝商品
     * @return mixed
     */
    public function copy()
    {
        if ($this->request->isAjax()) {
            $data = $this->request->param();
            unset($data['goods_id']);
            $data['uid']     = $this->getUid();
            $data['site_id'] = $this->getSiteId();
            $data['is_attr'] = $this->request->has('is_attr') ? '1' : '0';
            $result          = $this->validate($data, 'ShopGoodsValidate');
            if ($result !== true) {
                $this->error($result);
            }
            if (!$this->request->has('extend')) {
                $data['extend'] = '';
            }
            $result = $this->goodsModel->addData($data);
            if ($result == false) {
                $this->error($this->goodsModel->getError());
            }
            $this->success('拷贝成功', cookie('__GOODSURL__'));
        }
        $goodsId = $this->request->param('goods_id/d');
        $info    = $this->goodsModel->getInfo($goodsId);
        //sku信息
        if ($info['is_attr'] == 1) {
            $attrModel = new ShopAttrModel();
            $attrIds   = $this->goodsCategoryCache[$info['cid']]['attr_ids'];
            $attrList  = $attrModel->getAttrList($attrIds);
            $this->assign('attrList', $attrList);
        }
        //扩展信息
        $extendList = $this->extendModel->where('site_id', $this->getSiteId())->order('extend_sort')->select();
        $this->assign('unitList', get_dict('103'));
        $this->assign('extendList', $extendList);
        $this->assign('goodsCategory', $this->goodsCategoryCache);
        $this->assign('info', $info);
        $this->assign('utype',$this->getUtype());
        return $this->fetch();
    }

    /**
     * 设置状态
     */
    public function setStatus()
    {
        $goodsId = $this->request->param('goods_id');
        $field   = $this->request->param('field');
        $status  = $this->request->param('status');
        $this->goodsModel->where('goods_id', $goodsId)->setField($field, $status);
        $this->success('切换状态成功！');
    }

    /**
     * 删除
     */
    public function del()
    {
        $goodsId = $this->request->param('goods_id/d');
        $this->goodsModel->delData($goodsId);
        $this->success('删除成功！');
    }

    /**
     *排序
     */
    public function updateOrder()
    {
        $listOrder = $this->request->param('list_order/a');
        foreach ($listOrder as $goods_id => $goods_sort) {
            $goodsId    = intval($goods_id);
            $goodsSort  = intval($goods_sort);
            $dataList[] = ["goods_id" => $goodsId, "goods_sort" => $goodsSort];
        }
        $this->goodsModel->saveAll($dataList);
        $this->success('排序成功！');
    }

    /**
     * 删除单条SKU
     */
    public function delSku()
    {
        $skuId = $this->request->param('sku_id');
        $this->goodsSkuModel->delData($skuId);
        $this->success('操作成功！');
    }

    /**
     * 阶梯价
     */
    public function ladderprice()
    {
        return $this->fetch();
    }

    /**
     * 获取指定栏目下品牌
     * @return \think\response\Json
     */
    public function getCidBrand()
    {
        $brandModel = new ShopGoodsBrandModel();
        $brandList  = [];
        $cid        = $this->request->param('cid/d');
        $list       = $brandModel
            ->field('brand_content', true)
            ->where('site_id', $this->getSiteId())
            ->where("find_in_set('{$cid}',cids)")
            ->order('brand_sort desc')
            ->select();
        if (!$list->isEmpty()) {
            $brandList = $list;
        }
        return json($brandList);
    }

    /**
     * 获取栏目绑定属性
     */
    public function getAttr()
    {
        $cid    = $this->request->param('cid/d', 0);
        $isShow = 0; //不显示SKU属性
        if ($cid > 0) {
            $attrIds = $this->goodsCategoryCache[$cid]['attr_ids'];
            if (!empty($attrIds)) { //绑定SKU得栏目
                $attrModel = new ShopAttrModel();
                $attrList  = $attrModel->getAttrList($attrIds);
                $isShow    = 1;
                $this->assign('attrList', $attrList);
            }
        }
        $this->assign('isShow', $isShow);
        echo $this->fetch();
    }

    /**
     * 获取扩展html
     */
    public function extend()
    {
        $goods_id = $this->request->param('goods_id');
        $extendId = $this->request->param('extend_id');
        $formHtml = $this->extendModel->getExtendHtml($extendId, $goods_id);
        $this->assign('formHtml', $formHtml);
        echo $this->fetch();
    }

}
